package com.onesports.intelligent.k12.polarlight.common.utils;

import cn.oneframework.common.utils.MessageUtils;
import cn.oneframework.common.utils.spring.SpringUtils;
import com.onesports.intelligent.k12.polarlight.config.DfsConfigurationProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.PictureData;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 文件处理工具类
 *
 * @author onesports
 */
@Slf4j
public class FileUtils {
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 获取系统临时目录
     *
     * @return
     */
    public static String getTemp() {
        return System.getProperty("java.io.tmpdir");
    }

    /**
     * 创建临时文件
     *
     * @param filePath
     * @param data
     * @return
     */
    public static File createTempFile(String filePath, byte[] data) throws IOException {
        String temp = getTemp() + filePath;
        File file = new File(temp);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data, 0, data.length);
        fos.flush();
        fos.close();
        return file;
    }

    public static String uploadImage(PictureData data) throws Exception {
        DfsConfigurationProperties dfsConfigurationProperties = SpringUtils.getBean(DfsConfigurationProperties.class);
        String domain = dfsConfigurationProperties.getDomain();
        String path = dfsConfigurationProperties.getPath();
        String uuid = UUID.randomUUID().toString();
        String file = path + uuid + "." + data.suggestFileExtension();
        log.info("=========================file=" + file);
        log.info("=========================file=" + file);
        log.info("=========================file=" + file);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(data.getData());
            fileOutputStream.flush();
//            HashMap<String, Object> paramMap = Maps.newHashMap();
//            paramMap.put("files", new File[]{FileUtil.file(file)});
//            paramMap.put("model", "wuhan_official_photo");

//            File fileFile = FileUtil.file(file);
//            FileInputStream input = new FileInputStream(file);
//            MultipartFile multipartFile =new MockMultipartFile("file", fileFile.getName(), "text/plain", IOUtils.toByteArray(input));
//
//            SysFileService sysFileService = SpringUtils.getBean(DfsConfigurationProperties.class);
//            List<SysFileVO> sysFileVOList = sysFileService.upload(new File[]{FileUtil.file(file)}, "", "excel", Boolean.TRUE);
//            String rs = HttpUtil.post(url, paramMap);
//            JSONObject results = JSON.parseObject(rs);
//            List<FileDTO> fileDTOS = JSON.parseArray(results.getString(BizKeysConstants.DATA),FileDTO.class);
//            if (results.getInteger(BizKeysConstants.CODE) == HttpStatus.OK.value() && CollectionUtils.isNotEmpty(fileDTOS)) {
//                return fileDTOS.get(0).getUrl();
//            }
//            if(sysFileVOList.size() > 0){
//                return sysFileVOList.get(0).getUrl() ;
//            }
            return domain + "/" + uuid + "." + data.suggestFileExtension();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception(MessageUtils.message("poi.importImageError"));
        } finally {
//            FileUtil.del(file);
        }
//        return null;

    }

    /**
     * 文件路径回溯校验(文件名是否包含"./"以及"../")
     *
     * @param path
     * @return
     */
    public static boolean isBacktrack(String path) {
        // 通过使用File.separator 无法过滤windows下的回溯
        return path.contains(".\\") || path.contains("..\\") || path.contains("../") || path.contains("./");
        //return path.contains("." + File.separator) || path.contains(".." + File.separator);
    }
}
